<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="性能优化," />


<meta name="description" content="前端优化减少http请求数 图片地图。客户单图片地图可以使用map标签来实现。如果正在导航或者其他超链接中使用多个图片，将他们转换为图片地图是加速页面的最简单的方式。   CSS Sprites。将多幅图片合并成单独的图片。使用CSS的background-position属性，可以将HTML元素放置到背景图片期望的位置上。   内联图片。使用data:URL模式可以在Web页面中包含图片但无需额">
<meta name="keywords" content="性能优化">
<meta property="og:type" content="article">
<meta property="og:title" content="网站性能优化">
<meta property="og:url" content="http://blog.yunshu168.com/posts/c8d87eec.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="前端优化减少http请求数 图片地图。客户单图片地图可以使用map标签来实现。如果正在导航或者其他超链接中使用多个图片，将他们转换为图片地图是加速页面的最简单的方式。   CSS Sprites。将多幅图片合并成单独的图片。使用CSS的background-position属性，可以将HTML元素放置到背景图片期望的位置上。   内联图片。使用data:URL模式可以在Web页面中包含图片但无需额">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://static.yunshudm.com/2017/3/261652573847931.png">
<meta property="og:image" content="http://static.yunshudm.com/2017/3/wKiom1LUF8DS1inQAAE8bwOlNT22220.png">
<meta property="og:updated_time" content="2019-12-04T11:25:35.773Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="网站性能优化">
<meta name="twitter:description" content="前端优化减少http请求数 图片地图。客户单图片地图可以使用map标签来实现。如果正在导航或者其他超链接中使用多个图片，将他们转换为图片地图是加速页面的最简单的方式。   CSS Sprites。将多幅图片合并成单独的图片。使用CSS的background-position属性，可以将HTML元素放置到背景图片期望的位置上。   内联图片。使用data:URL模式可以在Web页面中包含图片但无需额">
<meta name="twitter:image" content="http://static.yunshudm.com/2017/3/261652573847931.png">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/c8d87eec.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>网站性能优化 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/c8d87eec.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">网站性能优化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-25T21:47:41+08:00">2018-03-25</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前端优化"><a href="#前端优化" class="headerlink" title="前端优化"></a>前端优化</h2><h3 id="减少http请求数"><a href="#减少http请求数" class="headerlink" title="减少http请求数"></a>减少http请求数</h3><ul>
<li>图片地图。客户单图片地图可以使用<a href="http://www.w3school.com.cn/tags/tag_map.asp" target="_blank" rel="noopener">map</a>标签来实现。如果正在导航或者其他超链接中使用多个图片，将他们转换为图片地图是加速页面的最简单的方式。</li>
</ul>
<ul>
<li>CSS Sprites。将多幅图片合并成单独的图片。使用CSS的<a href="http://www.w3school.com.cn/cssref/pr_background-position.asp" target="_blank" rel="noopener">background-position</a>属性，可以将HTML元素放置到背景图片期望的位置上。</li>
</ul>
<ul>
<li>内联图片。使用data:URL模式可以在Web页面中包含图片但无需额外的HTTP请求。</li>
</ul>
<ul>
<li>合并脚本和样式表。理想情况下，一个页面应该使用不多于一个脚本和样式表。</li>
</ul>
<a id="more"></a>
<h3 id="使用CDN存储前端资源"><a href="#使用CDN存储前端资源" class="headerlink" title="使用CDN存储前端资源"></a>使用CDN存储前端资源</h3><p>CDN用于发布静态内容，如图片、脚本、样式和Flash。</p>
<p>可使用<a href="http://17ce.com" target="_blank" rel="noopener">http://17ce.com</a>这个网站网站使用CDN后在各地的响应速度。</p>
<h3 id="添加Expires头"><a href="#添加Expires头" class="headerlink" title="添加Expires头"></a>添加Expires头</h3><h3 id="充分利用浏览器缓存"><a href="#充分利用浏览器缓存" class="headerlink" title="充分利用浏览器缓存"></a>充分利用浏览器缓存</h3><h3 id="多域名访问前端资源"><a href="#多域名访问前端资源" class="headerlink" title="多域名访问前端资源"></a>多域名访问前端资源</h3><h3 id="使用单独的静态资源域名。"><a href="#使用单独的静态资源域名。" class="headerlink" title="使用单独的静态资源域名。"></a>使用单独的静态资源域名。</h3><h3 id="资源数据的压缩"><a href="#资源数据的压缩" class="headerlink" title="资源数据的压缩"></a>资源数据的压缩</h3><h3 id="压缩代码大小、图片大小，开启服务器gzip压缩"><a href="#压缩代码大小、图片大小，开启服务器gzip压缩" class="headerlink" title="压缩代码大小、图片大小，开启服务器gzip压缩"></a>压缩代码大小、图片大小，开启服务器gzip压缩</h3><h3 id="优化首屏展示速度"><a href="#优化首屏展示速度" class="headerlink" title="优化首屏展示速度"></a>优化首屏展示速度</h3><blockquote>
<p>延迟加载、异步加载</p>
</blockquote>
<p> 扩展阅读：</p>
<ul>
<li><a href="http://www.cnblogs.com/paul-3/p/5999722.html" target="_blank" rel="noopener">雅虎34条军规</a></li>
</ul>
<ul>
<li><a href="http://yslow.org/" target="_blank" rel="noopener">Yslow Web性能测试插件</a></li>
</ul>
<h2 id="php优化"><a href="#php优化" class="headerlink" title="php优化"></a>php优化</h2><h3 id="使用opcode缓存"><a href="#使用opcode缓存" class="headerlink" title="使用opcode缓存"></a>使用opcode缓存</h3><h4 id="opcode缓存简介"><a href="#opcode缓存简介" class="headerlink" title="opcode缓存简介"></a>opcode缓存简介</h4><blockquote>
<p>当解释器完成对脚本代码的分析后，便将它们生成可以直接运行的中间代码，也称为操作码（Operate Code，opcode）。Opcode cache的目地是避免重复编译，减少CPU和内存开销。如果动态内容的性能瓶颈不在于CPU和内存，而在于I/O操作，比如数据库查询带来的磁盘I/O开销，那么opcode cache的性能提升是非常有限的。</p>
</blockquote>
<h4 id="使用opcode缓存-1"><a href="#使用opcode缓存-1" class="headerlink" title="使用opcode缓存"></a>使用opcode缓存</h4><p><img src="http://static.yunshudm.com/2017/3/261652573847931.png" alt="opcode-cache"></p>
<p>从图中可以看出，使用了opcode缓存后，php代码的生命周期少了词典扫描和表达式（将PHP代码转换为语言片段[Tokens]）、解析文件（将Tokens转换成简单而有意义的表达式）、创建要执行的计算机代码（称为Opcode）几步。</p>
<h4 id="opecode缓存-Zend-OPcache安装使用"><a href="#opecode缓存-Zend-OPcache安装使用" class="headerlink" title="opecode缓存-Zend OPcache安装使用"></a>opecode缓存-Zend OPcache安装使用</h4><p>PHP&gt;=5.5.0，php内置了OPcache,PHP小于5.5.0的话，要通过PCEL安装。</p>
<p><strong>OPcache配置</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">#检查脚本时间戳是否有更新的周期，以秒为单位。 设置为0会导致针对每个请求，OPcache都会检查脚本更新。</span><br><span class="line">opcache.revalidate_freq=60</span><br><span class="line">#如果启用，那么 OPcache 会每隔 opcache.revalidate_freq 设定的秒数 检查脚本是否更新。 如果禁用此选项，你必须使用 opcache_reset() 或者 opcache_invalidate() 函数来手动重置 OPcache，也可以 通过重启 Web 服务器来使文件系统更改生效</span><br><span class="line">opcache.validate_timestamps=1 </span><br><span class="line">#OPcache 哈希表中可存储的脚本文件数量上限。 真实的取值是在质数集合 &#123; 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 &#125; 中找到的第一个大于等于设置值的质数。 设置值取值范围最小值是 200，最大值在 PHP 5.5.6 之前是 100000，PHP 5.5.6 及之后是 1000000</span><br><span class="line">opcache.max_accelerated_files=1000</span><br><span class="line">#OPcache 的共享内存大小，以兆字节为单位。</span><br><span class="line">opcache.memory_consumption=512</span><br><span class="line"># 用来存储预留字符串的内存大小，以兆字节为单位。 PHP 5.3.0 之前的版本会忽略此配置指令。</span><br><span class="line">opcache.interned_strings_buffer=16</span><br><span class="line">#如果启用，则会使用快速停止续发事件。 所谓快速停止续发事件是指依赖 Zend 引擎的内存管理模块 一次释放全部请求变量的内存，而不是依次释放每一个已分配的内存块。</span><br><span class="line">opcache.fast_shutdown=1</span><br></pre></td></tr></table></figure>
<h3 id="PHP-7"><a href="#PHP-7" class="headerlink" title="PHP 7"></a>PHP 7</h3><p>PHP 7相对比PHP 5.*,性能有了质的飞跃。PHP7相对于php5.6有2~3倍的性能提升。目前PHP的最新版本是PHP 7.2.5，相对于PHP 7.1也有部分性能提升。</p>
<p>性能评测文章参考：</p>
<p><a href="http://www.laruence.com/2016/12/18/3137.html" target="_blank" rel="noopener">PHP的性能演进(从PHP5.0到PHP7.1的性能全评测</a><br><a href="https://mengkang.net/1019.html" target="_blank" rel="noopener">PHP7.2、PHP7.1 性能对比</a></p>
<h3 id="SWOOLE"><a href="#SWOOLE" class="headerlink" title="SWOOLE"></a>SWOOLE</h3><p>Swoole是一款常驻内存的 PHP C扩展，Swoole提供了协程、Http Server、Tcp Server、UDP Server、<br>Websocket Server、定时器等功能</p>
<h3 id="php性能分析-xhui-tideways实践"><a href="#php性能分析-xhui-tideways实践" class="headerlink" title="php性能分析 xhui + tideways实践"></a>php性能分析 xhui + tideways实践</h3><blockquote>
<p>tiways是一个测试php性能的php扩展，php版本要求是大于等于7.0。如果php版本小于7.0，可以使用xhprof扩展。<br>xhgui用来展示测试数据，xhgui将数据保存到MongoDB。</p>
</blockquote>
<h4 id="安装tideways"><a href="#安装tideways" class="headerlink" title="安装tideways"></a>安装tideways</h4><p>在ubuntu环境下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">echo &apos;deb http://s3-eu-west-1.amazonaws.com/qafoo-profiler/packages debian main&apos; &gt; /etc/apt/sources.list.d/tideways.list</span><br><span class="line">wget -qO - https://s3-eu-west-1.amazonaws.com/qafoo-profiler/packages/EEB5E8F4.gpg | sudo apt-key add -</span><br><span class="line">sudo apt-get update</span><br><span class="line">sudo apt-get install tideways-php tideways-daemon</span><br></pre></td></tr></table></figure>
<p>重启php-fpm，查看是否安装成功：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo service php7.1-fpm restart</span><br></pre></td></tr></table></figure>
<h4 id="安装MongoDB"><a href="#安装MongoDB" class="headerlink" title="安装MongoDB"></a>安装MongoDB</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sudo apt-get install mongodb</span><br><span class="line">sudo apt-get install  php-mongodb</span><br><span class="line">sudo /etc/init.d/mongodb start</span><br></pre></td></tr></table></figure>
<h4 id="安装xhgui"><a href="#安装xhgui" class="headerlink" title="安装xhgui"></a>安装xhgui</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">git clone https://github.com/laynefyc/xhgui-branch.git</span><br><span class="line">cd xhgui-branch</span><br><span class="line">composer install</span><br></pre></td></tr></table></figure>
<h4 id="配置xhgui"><a href="#配置xhgui" class="headerlink" title="配置xhgui"></a>配置xhgui</h4><p>添加config/config.php,添加支持扩展为<code>tideways</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">return [</span><br><span class="line">    &apos;extension&apos; =&gt; &apos;tideways&apos;,</span><br><span class="line">];</span><br></pre></td></tr></table></figure>
<h4 id="MongoDB加索引"><a href="#MongoDB加索引" class="headerlink" title="MongoDB加索引"></a>MongoDB加索引</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ mongo</span><br><span class="line"> &gt; use xhprof</span><br><span class="line"> &gt; db.results.ensureIndex( &#123; &apos;meta.SERVER.REQUEST_TIME&apos; : -1 &#125; )</span><br><span class="line"> &gt; db.results.ensureIndex( &#123; &apos;profile.main().wt&apos; : -1 &#125; )</span><br><span class="line"> &gt; db.results.ensureIndex( &#123; &apos;profile.main().mu&apos; : -1 &#125; )</span><br><span class="line"> &gt; db.results.ensureIndex( &#123; &apos;profile.main().cpu&apos; : -1 &#125; )</span><br><span class="line"> &gt; db.results.ensureIndex( &#123; &apos;meta.url&apos; : 1 &#125; )</span><br></pre></td></tr></table></figure>
<h4 id="配置nginx"><a href="#配置nginx" class="headerlink" title="配置nginx"></a>配置nginx</h4><h5 id="1-要监控的应用"><a href="#1-要监控的应用" class="headerlink" title="1.要监控的应用"></a>1.要监控的应用</h5> <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"> location ~ \.php$ &#123;</span><br><span class="line">    fastcgi_split_path_info ^(.+\.php)(/.+)$;</span><br><span class="line">    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;</span><br><span class="line">    fastcgi_index index.php;</span><br><span class="line">    include fastcgi_params;</span><br><span class="line">    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;</span><br><span class="line">    	</span><br><span class="line">#加上下面的这两句</span><br><span class="line">    fastcgi_param TIDEWAYS_SAMPLERATE &quot;25&quot;;</span><br><span class="line">    fastcgi_param PHP_VALUE &quot;auto_prepend_file=/home/vagrant/Code/xhgui/external/header.php&quot;;</span><br><span class="line"></span><br><span class="line">    fastcgi_intercept_errors off;</span><br><span class="line">    fastcgi_buffer_size 16k;</span><br><span class="line">    fastcgi_buffers 4 16k;</span><br><span class="line">    fastcgi_connect_timeout 300;</span><br><span class="line">    fastcgi_send_timeout 300;</span><br><span class="line">    fastcgi_read_timeout 300;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="2-分析平台应用"><a href="#2-分析平台应用" class="headerlink" title="2.分析平台应用"></a>2.分析平台应用</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">#表示省略了一些nginx配置</span><br><span class="line">server &#123;</span><br><span class="line">    listen 80;</span><br><span class="line">    listen 443 ssl http2;</span><br><span class="line">    server_name xhgui.app;</span><br><span class="line">    root &quot;/home/vagrant/Code/xhgui/webroot&quot;;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="性能分析平台搭建效果"><a href="#性能分析平台搭建效果" class="headerlink" title="性能分析平台搭建效果"></a>性能分析平台搭建效果</h4><p><img src="http://static.yunshudm.com/2017/3/wKiom1LUF8DS1inQAAE8bwOlNT22220.png" alt="xhgui"></p>
<p>相关链接 ：</p>
<ul>
<li><a href="https://github.com/tideways/php-xhprof-extension" target="_blank" rel="noopener">https://github.com/tideways/php-xhprof-extension</a></li>
<li><a href="https://tideways.io/profiler/docs/setup/installation" target="_blank" rel="noopener">https://tideways.io/profiler/docs/setup/installation</a></li>
<li><a href="https://github.com/laynefyc/xhgui-branch.git" target="_blank" rel="noopener">https://github.com/laynefyc/xhgui-branch.git</a></li>
<li><a href="https://segmentfault.com/a/1190000003509917" target="_blank" rel="noopener">使用XHProf查找PHP性能瓶颈</a></li>
</ul>
<h2 id="Mysql优化"><a href="#Mysql优化" class="headerlink" title="Mysql优化"></a>Mysql优化</h2><h3 id="表的设计优化"><a href="#表的设计优化" class="headerlink" title="表的设计优化"></a>表的设计优化</h3><ul>
<li>添加主键索引</li>
</ul>
<p>innodb需要有一个主键，主键不要有业务用途。</p>
<ul>
<li><p>表的字段类型选择</p>
<ul>
<li><p>能选短整形，就不要选长整型</p>
</li>
<li><p>能选char就避免varchar</p>
</li>
<li><p>使用varchar类型的时候，长度够用就行</p>
</li>
<li><p>大字段考虑分开存储</p>
</li>
<li><p>字段适当冗余</p>
</li>
</ul>
</li>
</ul>
<h3 id="索引的优化"><a href="#索引的优化" class="headerlink" title="索引的优化"></a>索引的优化</h3><ul>
<li><p>索引不要建太多</p>
<p>在修改数据时，每个索引都要进行更新，降低写速度。</p>
</li>
<li><p>使用覆盖索引</p>
</li>
<li><p>explain分析sql语句的执行计划</p>
</li>
</ul>
<p>示例：</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt; explain select * from typecho_contents where cid=40;</span><br><span class="line">+----+-------------+------------------+------------+-------+---------------+---------+---------+-------+------+----------+-------+</span><br><span class="line">| id | select_type | table            | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra |</span><br><span class="line">+----+-------------+------------------+------------+-------+---------------+---------+---------+-------+------+----------+-------+</span><br><span class="line">|  1 | SIMPLE      | typecho_contents | NULL       | const | PRIMARY       | PRIMARY | 4       | const |    1 |   100.00 | NULL  |</span><br><span class="line">+----+-------------+------------------+------------+-------+---------------+---------+---------+-------+------+----------+-------+</span><br></pre></td></tr></table></figure>
<p>重要列：</p>
<p>type - 连接使用的类型</p>
<p>链接类型从最佳到最坏：<br>system &gt; const &gt; eq_ref &gt; ref &gt; fulltext &gt; ref_or_null &gt; index_merge &gt; unique_subquery &gt; index_subquery &gt; range &gt; index &gt; ALL</p>
<p>解释：</p>
<pre>
system:表仅有一行(=系统表)。这是const联接类型的一个特例。
const:表最多有一个匹配行,它将在查询开始时被读取。因为仅有一行,在这行的列值可被优化器剩余部分认为是常数。const表很快,因为它们只读取一次!
eq_ref:对于每个来自于前面的表的行组合,从该表中读取一行。这可能是最好的联接类型,除了const类型。
ref:对于每个来自于前面的表的行组合,所有有匹配索引值的行将从这张表中读取。
ref_or_null:该联接类型如同ref,但是添加了MySQL可以专门搜索包含NULL值的行。
index_merge:该联接类型表示使用了索引合并优化方法。
unique_subquery:该类型替换了下面形式的IN子查询的ref: value IN (SELECT primary_key FROM single_table WHERE some_expr) unique_subquery是一个索引查找函数,可以完全替换子查询,效率更高。
index_subquery:该联接类型类似于unique_subquery。可以替换IN子查询,但只适合下列形式的子查询中的非唯一索引: value IN (SELECT key_column FROM single_table WHERE some_expr)
range:只检索给定范围的行,使用一个索引来选择行。
index:该联接类型与ALL相同,除了只有索引树被扫描。这通常比ALL快,因为索引文件通常比数据文件小。
</pre>

<p>一般来说，得保证查询至少达到range级别，最好能达到ref，否则就可能会出现性能问题。</p>
<p>key: Mysql实际使用的索引</p>
<p>Extra:</p>
<ul>
<li>Using filesort: Mysql需要额外的步骤排序，表示语句需要优化</li>
<li>Using temporary： 使用到临时表来存储查询结果，表示语句需要优化</li>
</ul>
<h3 id="SQL查询优化"><a href="#SQL查询优化" class="headerlink" title="SQL查询优化"></a>SQL查询优化</h3><h4 id="通过慢查询日志获取存在性能问题的SQL"><a href="#通过慢查询日志获取存在性能问题的SQL" class="headerlink" title="通过慢查询日志获取存在性能问题的SQL"></a>通过慢查询日志获取存在性能问题的SQL</h4><h5 id="慢查询日志分析工具"><a href="#慢查询日志分析工具" class="headerlink" title="慢查询日志分析工具"></a>慢查询日志分析工具</h5><p>相关配置参数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">slow_query_log # 启动停止记录慢查日志，慢查询日志默认是没有开启的可以在配置文件中开启(on)</span><br><span class="line"></span><br><span class="line">slow_query_log_file # 指定慢查日志的存储路径及文件，日志存储和数据存储应该分开存储</span><br><span class="line"></span><br><span class="line">long_query_time # 指定记录慢查询日志SQL执行时间的阀值默认值为10秒通常,对于一个繁忙的系统来说,改为0.001秒(1毫秒)比较合适</span><br><span class="line"></span><br><span class="line">log_queries_not_using_indexes # 是否记录未使用索引的SQL</span><br></pre></td></tr></table></figure>
<p>工具：<code>pt-query-digest</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pt-query-digest --explain h=127.0.0.1,u=root,p=123456  slow-mysql.log</span><br></pre></td></tr></table></figure>
<blockquote>
<p>pt-query-digest是用于分析mysql慢查询的一个工具，它可以分析binlog、General log、slowlog。可以把分析结果输出到文件中，也可以对SHOW PROCESSLIST或者通过tcpdump抓取的MySQL协议数据进行分析。分析过程是先对查询语句的条件进行参数化，然后对参数化以后的查询进行分组统计，统计出各查询的执行时间、次数、占比等，可以借助分析结果找出问题。</p>
</blockquote>
<p><strong>pt-query-digest工具的安装</strong></p>
<p>因为pt-query-digest是包含在percona-tookit工具集中的，所以只要安装percona-tookit即可。percona-tookie链接：<a href="https://www.percona.com/doc/percona-toolkit/3.0/installation.html" target="_blank" rel="noopener">https://www.percona.com/doc/percona-toolkit/3.0/installation.html</a></p>
<p><strong>pt-query-digest工具的使用参考</strong></p>
<p><a href="https://www.cnblogs.com/luyucheng/p/6265873.html" target="_blank" rel="noopener">https://www.cnblogs.com/luyucheng/p/6265873.html</a></p>
<h4 id="实时获取存在性能问题的SQL"><a href="#实时获取存在性能问题的SQL" class="headerlink" title="实时获取存在性能问题的SQL"></a>实时获取存在性能问题的SQL</h4><h5 id="直接通过表查询"><a href="#直接通过表查询" class="headerlink" title="直接通过表查询"></a>直接通过表查询</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">SELECT id,user,host,DB,command,time,state,info</span><br><span class="line">FROM information_schema.processlist</span><br><span class="line">WHERE TIME&gt;=1</span><br></pre></td></tr></table></figure>
<p>查询当前服务器执行超过1s的SQL，可以通过脚本周期性的来执行这条SQL，就能查出有问题的SQL。</p>
<h5 id="通过pt-query-digst来分析"><a href="#通过pt-query-digst来分析" class="headerlink" title="通过pt-query-digst来分析"></a>通过pt-query-digst来分析</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pt-query-digest --processlist h=host1</span><br></pre></td></tr></table></figure>
<h4 id="特定SQL的查询优化"><a href="#特定SQL的查询优化" class="headerlink" title="特定SQL的查询优化"></a>特定SQL的查询优化</h4><h5 id="优化not-in和-lt-gt-查询"><a href="#优化not-in和-lt-gt-查询" class="headerlink" title="优化not in和&lt;&gt;查询"></a>优化not in和&lt;&gt;查询</h5><p>子查询改写为关联查询</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">select id,name </span><br><span class="line">from a </span><br><span class="line">where id </span><br><span class="line">not in (select id from b)</span><br></pre></td></tr></table></figure>
<p>改写后：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">select id,name </span><br><span class="line">from a </span><br><span class="line">left join b on a.id=b.id</span><br><span class="line">where b.id is null</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/c8d87eec.html" title="网站性能优化">http://blog.yunshu168.com/posts/c8d87eec.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/性能优化/" rel="tag"># 性能优化</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/724b0e67.html" rel="next" title="Mysql数据库学习总结">
                <i class="fa fa-chevron-left"></i> Mysql数据库学习总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/e4000784.html" rel="prev" title="数据库扩展">
                数据库扩展 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前端优化"><span class="nav-number">1.</span> <span class="nav-text">前端优化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#减少http请求数"><span class="nav-number">1.1.</span> <span class="nav-text">减少http请求数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用CDN存储前端资源"><span class="nav-number">1.2.</span> <span class="nav-text">使用CDN存储前端资源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加Expires头"><span class="nav-number">1.3.</span> <span class="nav-text">添加Expires头</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#充分利用浏览器缓存"><span class="nav-number">1.4.</span> <span class="nav-text">充分利用浏览器缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多域名访问前端资源"><span class="nav-number">1.5.</span> <span class="nav-text">多域名访问前端资源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用单独的静态资源域名。"><span class="nav-number">1.6.</span> <span class="nav-text">使用单独的静态资源域名。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#资源数据的压缩"><span class="nav-number">1.7.</span> <span class="nav-text">资源数据的压缩</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#压缩代码大小、图片大小，开启服务器gzip压缩"><span class="nav-number">1.8.</span> <span class="nav-text">压缩代码大小、图片大小，开启服务器gzip压缩</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优化首屏展示速度"><span class="nav-number">1.9.</span> <span class="nav-text">优化首屏展示速度</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#php优化"><span class="nav-number">2.</span> <span class="nav-text">php优化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用opcode缓存"><span class="nav-number">2.1.</span> <span class="nav-text">使用opcode缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#opcode缓存简介"><span class="nav-number">2.1.1.</span> <span class="nav-text">opcode缓存简介</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用opcode缓存-1"><span class="nav-number">2.1.2.</span> <span class="nav-text">使用opcode缓存</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#opecode缓存-Zend-OPcache安装使用"><span class="nav-number">2.1.3.</span> <span class="nav-text">opecode缓存-Zend OPcache安装使用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PHP-7"><span class="nav-number">2.2.</span> <span class="nav-text">PHP 7</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SWOOLE"><span class="nav-number">2.3.</span> <span class="nav-text">SWOOLE</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#php性能分析-xhui-tideways实践"><span class="nav-number">2.4.</span> <span class="nav-text">php性能分析 xhui + tideways实践</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#安装tideways"><span class="nav-number">2.4.1.</span> <span class="nav-text">安装tideways</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#安装MongoDB"><span class="nav-number">2.4.2.</span> <span class="nav-text">安装MongoDB</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#安装xhgui"><span class="nav-number">2.4.3.</span> <span class="nav-text">安装xhgui</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置xhgui"><span class="nav-number">2.4.4.</span> <span class="nav-text">配置xhgui</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#MongoDB加索引"><span class="nav-number">2.4.5.</span> <span class="nav-text">MongoDB加索引</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置nginx"><span class="nav-number">2.4.6.</span> <span class="nav-text">配置nginx</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-要监控的应用"><span class="nav-number">2.4.6.1.</span> <span class="nav-text">1.要监控的应用</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-分析平台应用"><span class="nav-number">2.4.6.2.</span> <span class="nav-text">2.分析平台应用</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#性能分析平台搭建效果"><span class="nav-number">2.4.7.</span> <span class="nav-text">性能分析平台搭建效果</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Mysql优化"><span class="nav-number">3.</span> <span class="nav-text">Mysql优化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#表的设计优化"><span class="nav-number">3.1.</span> <span class="nav-text">表的设计优化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#索引的优化"><span class="nav-number">3.2.</span> <span class="nav-text">索引的优化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SQL查询优化"><span class="nav-number">3.3.</span> <span class="nav-text">SQL查询优化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#通过慢查询日志获取存在性能问题的SQL"><span class="nav-number">3.3.1.</span> <span class="nav-text">通过慢查询日志获取存在性能问题的SQL</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#慢查询日志分析工具"><span class="nav-number">3.3.1.1.</span> <span class="nav-text">慢查询日志分析工具</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#实时获取存在性能问题的SQL"><span class="nav-number">3.3.2.</span> <span class="nav-text">实时获取存在性能问题的SQL</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#直接通过表查询"><span class="nav-number">3.3.2.1.</span> <span class="nav-text">直接通过表查询</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#通过pt-query-digst来分析"><span class="nav-number">3.3.2.2.</span> <span class="nav-text">通过pt-query-digst来分析</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#特定SQL的查询优化"><span class="nav-number">3.3.3.</span> <span class="nav-text">特定SQL的查询优化</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#优化not-in和-lt-gt-查询"><span class="nav-number">3.3.3.1.</span> <span class="nav-text">优化not in和&lt;&gt;查询</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
